import { Model, Effect } from 'dva';
import { Reducer } from 'redux';
import { BiStatus } from '@/common/type/BiStatus';
import { add, remove, list, addList, update } from './service';

export interface NewProductRecommend {
  id: number;
  productId: number;
  productName: string;
  sort: number;
  recommendStatus: BiStatus;
}

export interface NewProductRecommendModelState {
  recommends: NewProductRecommend[];
}

export interface BrandModelType extends Model {
  namespace: 'newProductRecommend';
  state: NewProductRecommendModelState;
  effects: {
    query: Effect;
    addList: Effect;
    remove: Effect;
    update: Effect;
  };
  reducers: {
    refresh: Reducer<NewProductRecommendModelState>;
  };
}

const BrandModel: BrandModelType = {
  namespace: 'newProductRecommend',
  state: {
    recommends: [],
  },

  reducers: {
    refresh(state = { recommends: [] }, action) {
      return {
        ...state,
        recommends: action.recommends,
      };
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const response = yield call(list);
      yield put({
        type: 'refresh',
        recommends: response,
      });
    },
    *addList({ payload, callback }, { call, put }) {
      yield call(addList, payload);
      yield put({
        type: 'query',
      });
      callback();
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({
        type: 'query',
      });
    },
    *update({ payload }, { call, put }) {
      yield call(update, payload);
      yield put({
        type: 'query',
      });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname.startsWith('/marketing/newProduct')) {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default BrandModel;
